package cn.hx.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println(request.getRequestURL());
        String token = request.getParameter("token");
        if (token == null || "".equals(token)) {
            System.out.println("不存在token，直接放行");
            filterChain.doFilter(request, response);
            return;
        }

// 2、然后将查询到的 User对象的相关信息封装到UsernamePasswordAuthenticationToken对象中，然后将该对象存储到Security的上下文对象中
        if (PublicController.tokens.containsKey(token)) {
            Authentication authentication = PublicController.tokens.get(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            System.out.println(authentication.getPrincipal());
        }


        filterChain.doFilter(request, response);
    }
}
